Ext.namespace('cn.com.xinli.pdm.dml');

cn.com.xinli.pdm.dml.debug = false;

cn.com.xinli.pdm.dml.TableListPanel = Ext.extend(Ext.Panel,
{
	initComponent : function()
	{
		var pageSize = 20;
		var tableStore = new Ext.data.Store
		({
			autoload: false,
			url: 'listTable.action',
			reader: new Ext.data.JsonReader(
					{
						root: 'tableList',
						totalProperty: 'totalCount'
					},
					[
						{name: 'tableId', type: 'string', mapping: 'tableId'},
						{name: 'tableName', type: 'string', mapping: 'tableName'},
						{name: 'tableBusinessName', type: 'string', mapping: 'tableBusinessName'}
					])
		});

		var tableColumnModel = new Ext.grid.ColumnModel
		([
			new Ext.grid.CheckboxSelectionModel({singleSelect:true}),
			{id:'tableId',hidden: true,header: "序号",dataIndex: 'tableId',width: 100},
			{
				id:'tableName',header: "表名",dataIndex: 'tableName',width: 100
			},
			{
				id:'tableBusinessName',header: "业务名称",dataIndex: 'tableBusinessName',width: 100
			}
		]);

		var addTableBtn = new Ext.Button({id: 'addTableBtn', text: '新建表', iconCls : 'icon-add'});
		var editTableBtn = new Ext.Button({id: 'editTableBtn', text: '修改表', iconCls : 'icon-edit'});
		var delTableBtn = new Ext.Button({id: 'delTableBtn', text: '删除表', iconCls : 'icon-del'});
		var tableGrid =  new Ext.grid.GridPanel
		({
			region: 'center',
			frame:true,
			border: true,
			autoHeight : false,
			viewConfig: {forceFit : true},

			enableColumnMove: false,
			enableColumnResize: true,
			enableColumnHide: false,
			enableHdMenu: false,
			autoScroll: true,
			trackMouseOver : true,

			bodyStyle : 'width:100%',


			store: tableStore,
			loadMask : {msg : '数据加载中...'},
			cm: tableColumnModel,
			autoExpandColumn: 'emptyColumn',
			tbar:[addTableBtn, editTableBtn, delTableBtn],
			bbar : new Ext.PagingToolbar
					({
						pageSize : pageSize,
						store : tableStore,
						displayInfo : true,
						displayMsg : '第 {0} - {1} 条  共 {2} 条',
						emptyMsg : "没有记录"
					}),
			sm : new Ext.grid.RowSelectionModel({singleSelect : true})
		});

		var queryBtn = new Ext.Button({text : '', iconCls : 'icon-search'});
		var queryForm  = new Ext.FormPanel
		({
			region: 'north',
			height: 50,
			frame:true,
			border: true,
			layout: 'column',
			items:
				[
					{
						width:150,
						items:[{width: 150, id: 'keyWord', xtype: 'textfield', name: 'keyWord'}]
					},
					{
						items:[queryBtn]
					}
				]
		});

		Ext.apply(this, {layout:'border', items: [queryForm, tableGrid]});
		tableStore.load({params: {start:0, limit:pageSize}});
		queryBtn.on('click', function(){
			var keyWord = queryForm.getForm().findField('keyWord').getValue();
			tableGrid.getStore().load({params:{keyWord: keyWord, start:0, limit:pageSize}});
		});

		var openEditTableWindow = function(tableId)
		{
			var title = tableId ? '修改表': '新建表';
			new cn.com.xinli.pdm.dml.EditTableWindow({storeToRefresh : tableStore, title:title, modal:true, tableId: tableId}).show();
		}
		addTableBtn.on('click', function(){
				openEditTableWindow();
			}),

		editTableBtn.on('click', function(){
				var selectedTable = tableGrid.getSelectionModel().getSelected();
				if(!selectedTable)
				{
					Ext.Msg.show({
						title: '提示',
						msg: '请先选择要修改的数据表.',
						minWidth: 200,
						buttons: {ok:'关闭'},
						icon: Ext.MessageBox.INFO,
						animEl: 'editTableBtn'
					});
					return;
				}
				openEditTableWindow(selectedTable.get('tableId'));
			}),

		delTableBtn.on('click', function(){
			var selectedTable = tableGrid.getSelectionModel().getSelected();
			if(!selectedTable)
			{
				Ext.Msg.show({
					title: '提示',
					msg: '请先选择要删除的数据表.',
					minWidth: 200,
					buttons: {ok:'关闭'},
					icon: Ext.MessageBox.INFO,
					animEl: 'delTableBtn'
				});
				return;
			}
			Ext.Msg.show({
				title:'确认',
				msg: '您确定要删除数据表“' + selectedTable.get('tableBusinessName') + '”',
				buttons: {ok:'是', cancel:'否'},
				animEl: 'delTableBtn',
				fn: function(btn)
					{
						if(btn == 'ok')
						{
							ajaxRequest(
								'dropTable.action',
								{tableId: selectedTable.get('tableId')},
								null,
								function(result)
									{
										if(result.success)
										{
											tableGrid.getStore().reload();
										}else
										{
											Ext.Msg.alert('错误',
												'删除数据表“' + selectedTable.get('tableBusinessName') + '”出错，详细信息：' + result.message);
										}
									}
								);
						}
					},
				icon: Ext.MessageBox.QUESTION
			});
		});
		cn.com.xinli.pdm.dml.TableListPanel.superclass.initComponent.call(this);
	}
})

cn.com.xinli.pdm.dml.EditTableWindow = Ext.extend(Ext.Window,
{
	tableId: '',
	storeToRefresh: null,

	initComponent : function()
	{
		var tableInfoForm = new Ext.FormPanel({
			title: '表信息',
			region: 'north',
			height: 70,
			width: 300,
			labelAlign: 'right',
			frame:true,
			border: true,
			layout: 'column',

			items:
				[
					{
						columnWidth: 0.5,
						layout: 'form',
						items:[{xtype: 'hidden', name: 'tableId'},
								{xtype: 'textfield', name: 'tableName', fieldLabel: '表名'}]
					}
					,
					{
						columnWidth: 0.5,
						layout: 'form',
						items:[{xtype: 'textfield', name: 'tableBusinessName', fieldLabel: '业务名称'}]
					}
				]
		})

		var Column = Ext.data.Record.create([
	           {name: 'columnId', type: 'string'},
	           {name: 'fieldName', type: 'string'},
	           {name: 'businName', type: 'string'},
	           {name: 'fieldType', type: 'string'},
	           {name: 'nullAble', type: 'string'}
	      ]);

		var columnStore = new Ext.data.Store
		({
			autoload: false,
			url: 'listTableColumn.action?tableId=' + this.tableId,
			reader: new Ext.data.JsonReader(
					{
					},
					Column)
		});

		var filedTypeStore = new Ext.data.SimpleStore({
			fields: ['value', 'label'],
			data :
				[
					['INT', '整数'],
					['FLOAT', '浮点数'],
					['DATETIME', '日期时间'],
					['SHORT_STRING', '字符串(100)'],
					['LONG_STRING', '字符串(500)'],
					['MAX_STRING', '最大字符串'],
					['IMAGE', '附件']
				]
		});

		Ext.form.CN_Checkbox = Ext.extend(Ext.form.Checkbox,{
				checkedValue: '是',
				uncheckedValue: '否',
				getValue : function(){
					var checked = Ext.form.CN_Checkbox.superclass.getValue.call(this);
					return checked? this.checkedValue : this.uncheckedValue;
			    },
				setValue : function(v){
					if(v == this.checkedValue)
					{
						v = true;
					}else if(v == this.uncheckedValue)
					{
						v = false;
					}
					Ext.form.CN_Checkbox.superclass.setValue.call(this, v);
			    }
			})
		var fieldTypeRender = function(value)
			{
				for(var index = 0; index < filedTypeStore.getCount(); index++)
				{
					var record = filedTypeStore.getAt(index);
					if(value == record.data.value)
					{
						return record.data.label;
					}
				}
				return value;
			};
		var columnColumnModel = new Ext.grid.ColumnModel([
			new Ext.grid.CheckboxSelectionModel({singleSelect:true}),
			{
	           id:'columnId',
			   hidden: true,
	           header: "序号",
	           dataIndex: 'columnId'
			},
			{
	           id:'fieldName',
	           header: "列名",
	           dataIndex: 'fieldName',
	           editor: new Ext.form.TextField({
	               allowBlank: false
	           })
	        },
			{
	           id:'businName',
	           header: "业务名称",
	           dataIndex: 'businName',
	           editor: new Ext.form.TextField({
	               allowBlank: false
	           })
	        },
			{
	           id:'fieldType',
	           header: "数据类型",
	           dataIndex: 'fieldType',
	           width: 100,
	           renderer: fieldTypeRender,
	           editor: new Ext.form.ComboBox({
	               typeAhead: true,
	               triggerAction: 'all',
	               store:filedTypeStore,
	               valueField:'value',
				   displayField:'label',
			       mode: 'local',
	               selectOnFocus:true,
	               listClass: 'x-combo-list-small'
	            })
	        },
			{
	           header: "可以为空？",
	           dataIndex: 'nullAble',
	           width: 100,
				   editor: new Ext.form.CN_Checkbox()
	        }
   		]);

   		var columnGrid = new Ext.grid.EditorGridPanel({
   				id: 'columnGrid',
   				region: 'center',
				frame:false,
				border: true,
				viewConfig: {forceFit : true},

				enableColumnMove: false,
				enableColumnResize: true,
				enableColumnHide: false,
				enableHdMenu: false,
				autoScroll: true,
				trackMouseOver : true,

				width:600,
				height:500,
				bodyStyle : 'width:100%',

				title:'列信息',
				store: columnStore,
				loadMask : {msg : '数据加载中...'},
				cm: columnColumnModel,

		        clicksToEdit:1,
		        selModel: new Ext.grid.RowSelectionModel({singleSelect : true}),
		        tbar: [{
		        	iconCls: 'icon-add',
		            text: '增加列',
		            handler : function()
					{
		                var column = new Column({
								columnId:'',
								fieldName: 'NAME',
								businName: '列名',
								fieldType: 'SHORT_STRING',
								nullAble: '否'
		                });
		                columnGrid.stopEditing();
		                var lastRowIndex = columnStore.getCount();
		                columnStore.insert(lastRowIndex, column);
		                columnGrid.startEditing(lastRowIndex, 0);
		            }
		        },
				{
					iconCls: 'icon-del',
					text: '删除列',
		            handler : function()
					{
						if(columnGrid.getSelectionModel().getSelected())
						{
							columnStore.remove(columnGrid.getSelectionModel().getSelected());
						}
		            }
				},
				{
					iconCls: 'icon-refresh',
					text: '重设列',
		            handler : function()
					{
						columnStore.load();
		            }
				}
				]
		    });
		var saveTable = function(btn)
			{
				btn.disable();
				var form = tableInfoForm.getForm();
				var params = new Array();
				params['table.tableId'] = form.findField("tableId").getValue();
				params['table.tableName'] = form.findField("tableName").getValue();
				params['table.tableBusinessName'] = form.findField("tableBusinessName").getValue();
				if(!params['table.tableName'])
				{
					Ext.Msg.show({
						icon: Ext.MessageBox.INFO,
						title: '提示',
						msg: '您没有填写表名！',
						minWidth: 200,
						buttons: {ok:'关闭'},
						fn: function(btn)
						{
							form.findField("tableName").focus();
						}
					});
					btn.enable();
					form.findField("tableId").focus();
					return;
				}
				if(!params['table.tableBusinessName'])
				{
					Ext.Msg.show({
						icon: Ext.MessageBox.INFO,
						title: '提示',
						msg: '您没有填写业务名称！',
						minWidth: 200,
						buttons: {ok:'关闭'},
						fn: function(btn)
						{
							form.findField("tableBusinessName").focus();
						}
					});
					btn.enable();
					return;
				}
				if(columnStore.getCount() == 0)
				{
					Ext.Msg.show({
						title: '提示',
						msg: '您没有定义列信息！',
						minWidth: 200,
						buttons: {ok:'关闭'},
						icon: Ext.MessageBox.INFO,
						animEl: 'editTableBtn'
					});
					btn.enable();
					return;
				}
				var fieldNames = new Array();
				for(var index = 0; index < columnStore.getCount(); index++)
				{
					var record = columnStore.getAt(index);
					params['table.columns['+ index + "].columnId"] = record.get('columnId');
					params['table.columns['+ index + "].fieldName"] = record.get('fieldName');
					params['table.columns['+ index + "].businName"] = record.get('businName');
					params['table.columns['+ index + "].fieldType"] = record.get('fieldType');
					params['table.columns['+ index + "].nullAble"] = record.get('nullAble');
					var columnIndex = 0;
					var errMsg = '';
					if(fieldNames[record.get('fieldName')] == '')
					{
						errMsg = '列名必须填写！';
						columnIndex = 1;
					}else if(fieldNames[record.get('fieldName')])
					{
						errMsg = '与第' + fieldNames[record.get('fieldName')] + '行列名重复';
						columnIndex = 1;
					}else if(record.get('businName') == '')
					{
						errMsg = '业务名称必须填写！';
						columnIndex = 2;
					}
					fieldNames[record.get('fieldName')] = index+1;
					if(errMsg != '')
					{
						Ext.Msg.show({
							title: '提示',
							msg: '第' + (index+1) + '行,第' + columnIndex + '列数据不正确：'+ errMsg,
							minWidth: 200,
							buttons: {ok:'关闭'},
							icon: Ext.MessageBox.INFO,
							animEl: 'editTableBtn'
						});
						columnGrid.startEditing(index, columnIndex);
						btn.enable();
						return;
					}
				}
				var editTableWin = this.ownerCt;
				ajaxRequest(
					'saveTable.action',
					params,
					null,
					function(result){
						if(result.success)
						{
							editTableWin.storeToRefresh.reload();
							editTableWin.close();
						}else
						{
							Ext.Msg.alert('错误',
								'保存数据表“' + params['table.tableName'] + '”出错，详细信息：' + result.message);
							btn.enable();
						}
					});
			}
		Ext.apply(this, {
			height: 600,
			width: 600,
			layout:'border',
			buttonAlign: 'center',
			resizable: false,
			items: [tableInfoForm, columnGrid],
			buttons: [
				{text: '保存', handler: saveTable},
				{text: '取消',handler: function(){ this.ownerCt.close()}}]});
		cn.com.xinli.pdm.dml.EditTableWindow.superclass.initComponent.call(this);
		if(this.tableId)
		{
			ajaxRequest(
				'loadTable.action',
				{tableId: this.tableId},
				tableInfoForm,
				function(result){
					if(result.success)
					{
						var table = result.table;
						this.getForm().findField('tableId').setValue(table.tableId);
						this.getForm().findField('tableName').setValue(table.tableName);
						this.getForm().findField('tableBusinessName').setValue(table.tableBusinessName);
					}else
					{
						Ext.Msg.alert(
							'错误',
							'加载数据表信息出错!详细信息：' + result.message
						);
					}
				});
			columnStore.load();
		}
	}

})


Ext.reg('tableListPanel', cn.com.xinli.pdm.dml.TableListPanel);